package com.example.common.util.jwt;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class JwtUtil {

    private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);
    /**
     * 密钥
     */
    private static final String SECRET = "wcp";

    /**
     * 过期时间
     **/
    private static final long EXPIRATION = 1800L;//单位为秒

    /**
     * 生成用户token,设置token超时时间
     */
    public static String createToken(String json) {
        try {
            // 将JSON字符串转换为Map
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> userMap = objectMapper.readValue(json, Map.class);

            // 过期时间
            Date expireDate = new Date(System.currentTimeMillis() + EXPIRATION * 1000);

            Map<String, Object> map = new HashMap<>();
            map.put("alg", "HMAC256");
            map.put("typ", "JWT");

            JWTCreator.Builder builder = JWT.create()
                    .withHeader(map) // 添加头部
                    .withExpiresAt(expireDate) // 超时设置,设置过期的日期
                    .withIssuedAt(new Date()); // 签发时间

            // 将Map中的键值对添加到JWT的Claims中
            for (Map.Entry<String, Object> entry : userMap.entrySet()) {
                builder.withClaim(entry.getKey(), entry.getValue().toString());
            }

            // 返回完整的JWT字符串
            return builder.sign(Algorithm.HMAC256(SECRET)); // SECRET加密
        } catch (Exception e) {
            logger.error("Error creating token", e);
            return null;
        }
    }

    /**
     * 校验token并解析token
     */
    public static Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            logger.error(e.getMessage());
            logger.error("token解码异常");
            //解码异常则抛出异常
            return null;
        }
        return jwt.getClaims();
    }
}